const { Op, literal } = require("sequelize");
const Product = require("../models/Product.js");
const Category = require("../models/Category.js");

class ProductService {
    async addProduct(productData){
        return Product.create(productData);
    }
    async getProductById(id){
        return Product.findByPk(id);
    }
    async updateProduct(productData){
        return Product.update(productData, {
            where: {
                id: productData.id
            }
        });
    }
    async deleteProduct(productId){
        return Product.destroy({
            where: {
                id: productId
            }
        });
    }
    async getProductListByPage(page = 1, limit = 10, keyword){
        return Product.findAndCountAll({
            limit,
            offset: (page - 1) * limit,
            where: {
                deleted_at: null,
                [Op.or]: [
                    {
                      name: {
                        [Op.like]: `%${keyword}%`,
                      },
                    },
                    {
                      description: {
                        [Op.like]: `%${keyword}%`,
                      },
                    },
                  ],
            },
            attributes: [
                'id',
                'name',
                'price',
                'description',
                'category_id',
                [literal('DATE_FORMAT(Product.created_at, "%Y-%m-%d %H:%i:%s")'), 'created_at'],
                [literal('DATE_FORMAT(Product.updated_at, "%Y-%m-%d %H:%i:%s")'), 'updated_at'],
                [literal('DATE_FORMAT(Product.deleted_at, "%Y-%m-%d %H:%i:%s")'), 'deleted_at'],
            ],
            include: [
                {
                    model: Category,
                    as: 'category',
                    attributes: ['name']
                }
            ]
        });
    }
}

module.exports = new ProductService();